package z.ftpd;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class FtpActivity extends Activity {

	protected static Object server;

	private static final String sd0 = Environment.getExternalStorageDirectory().getAbsolutePath();

	protected static String sd = sd0;
	protected static int port = 2121;

	private Button b;
	private EditText dk;
	private AutoCompleteTextView lj;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		b = findViewById(R.id.b);
		lj = findViewById(R.id.lj);
		dk = findViewById(R.id.dk);

		lj.setText(sd);
		dk.setText(port + "");
		b.setText(server == null ? "启动" : "停止");

		var wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

		TextView tv = findViewById(R.id.t);

		if (wifiManager.isWifiEnabled())
			tv.setText("IP：" + toIp(wifiManager.getConnectionInfo().getIpAddress()));
		else try {
			var clazz = wifiManager.getClass();
			tv.setText(clazz.getDeclaredMethod("getWifiApState").invoke(wifiManager).equals(
					clazz.getDeclaredField("WIFI_AP_STATE_ENABLED").get(wifiManager)) ? "IP：192.168.43.1" : "WIFI未开启");
		} catch (Exception e) {
			tv.setText("无法获取热点状态");
		}

		lj.setText(sd);

		List<Map<String, String>> maps = new ArrayList<>();

		final class SA {
			private void add(final String first, final String second) {
				maps.add(new HashMap<>() {
					private static final long serialVersionUID = 0;

					{
						put("first", first);
						put("second", second);
					}

					@Override
					public String toString() {
						return first;
					}
				});
			}
		}


		var sa = new SA();
		sa.add(sd0, "内置存储器");
		var ssp = getSecondaryStoragePath();
		if (ssp != null) {
			sa.add(ssp, "外置存储器");
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
				var path = ssp + "/Android/data/" + getPackageName();
				sa.add(path, "外置存储器可写的目录");
				if (!new File(path).exists())
					getExternalFilesDir(null).getAbsolutePath();
			}
		}

		lj.setAdapter(new SimpleAdapter(this, maps,
				android.R.layout.simple_list_item_2, new String[]{"first", "second"},
				new int[]{android.R.id.text1, android.R.id.text2}) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				var view = super.getView(position, convertView, parent);
				view.setBackgroundColor(getResources().getColor(android.R.color.black));
				return view;
			}
		});
	}


	private void sync() {
		var t = lj.getText().toString();

		var f = new File(t);

		if (f.exists() && f.isDirectory()) sd = t;
		else {
			lj.setText(sd0);
			sd = sd0;
			popup(t + "文件夹不存在，已改为内置存储器");
		}

		t = dk.getText().toString();

		if (t.equals("")) {
			dk.setText("2121");
			port = 2121;
		} else port = Integer.parseInt(t);
	}

	protected abstract void stop() throws IOException;

	protected abstract void start() throws IOException;

	public void onClick(View view) throws IOException {
		if (server != null) {
			stop();
			server = null;
			popup("成功停止");
			b.setText("启动");
			return;
		}
		sync();
		start();
		popup("成功启动");
		b.setText("停止");
	}

	private String getSecondaryStoragePath() {
		try {
			var paths = new String[0];
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD)
				paths = (String[]) StorageManager.class.getMethod("getVolumePaths")
						.invoke(getSystemService(STORAGE_SERVICE));
			return paths.length <= 1 ? null : paths[1];
		} catch (Exception e) {
			return null;
		}
	}

	protected void popup(String tip) {
		Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_LONG).show();
	}

	private static String toIp(int j) {
		var s = "" + (j & 0xff);
		for (var i = 0; i < 3; i++)
			s += "." + ((j >>= 8) & 0xff);
		return s;
	}
}
